package controllers.listeners.semrep;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import models.FeaturesModel;

import objects.Constituent;
import objects.Feature;

import views.MainPanel;

/* Deletes the selected feature from the constituent if user-defined; sets feature to default otherwise */
/* actionPerformed when you click the "Delete Feature" button */
public class DeleteFeatureActionListener implements ActionListener {
	
	private MainPanel view;
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(view.getCurrCon() != null) {
			
			int row = view.getSelectedRow();
			
			String featureName = null;
			String featureValue = null;
			
			try {
				featureName = (String) view.getValueAt(row, view.findColumn("Name"));
				featureValue = (String) view.getValueAt(row, view.findColumn("Value"));
			}
			catch (Exception ex) {}
			
			if(featureName != null && featureValue != null && !featureName.equals("No features found")) {
				ArrayList<Feature> features = view.getCurrCon().getFeatures().getFeatureList();
				Feature feature = null;
				
				for (Constituent currentConstituent : FeaturesModel.getFeatures()) {
					if (view.getCurrCon().getLabel().equalsIgnoreCase(currentConstituent.getLabel())) {
						for (Feature currentFeature : currentConstituent.getFeatures().getFeatureList()) {
							if (currentFeature.getName().equals(featureName)) {
								feature = currentFeature;
								break;
							}
						}
					}
				}
				
				view.removeRow(row);
				
				for (Feature currentFeature : features) {
					if (currentFeature.getName().equals(featureName)) {
						if (feature.isEditable()) {
							features.remove(currentFeature);
						}
						else {
							view.insertRow(row, new String[] {featureName, feature.getValueList().get(0)});
							features.remove(currentFeature);
						}
						break;
					}
				}
			}
		}
	}
	
	public void setView(MainPanel view) {
		this.view = view;
	}
}
